<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Service;

use App\Constants\ListenerConst;
use App\Dao\SysConfigDao;
use Hyperf\Cache\Annotation\Cacheable;
use Hyperf\Cache\Listener\DeleteListenerEvent;

class SysConfigService extends AbstractService
{
    public const ALIPAY = 'ALI_PAY';

    public const BALANCE = 'BALANCE_PAY';

    public const WEPAY = 'WE_PAY';

    /**
     * @var SysConfigDao
     */
    public $dao;

    public function __construct(SysConfigDao $dao)
    {
        $this->dao = $dao;
    }

    #[Cacheable(prefix: 'SYS_CONFIG', value: 'key_#{key}', ttl: 9000, listener: ListenerConst::SYS_CONFIG_UPDATE)]
    public function getConfig($key)
    {
        $data = $this->dao->getModel()->newQuery()->where('key', '=', $key)
            ->first();
        if (!$data) {
            return [];
        }
        return json_decode($data['value'], true);
    }

    public function setConfig($key, $value)
    {
        if ($this->getConfig($key)) {
            $this->dao->updateRaw(['key' => $key], [
                'value' => json_encode($value),
            ]);
        } else {
            $this->dao->create([
                'key' => $key,
                'value' => json_encode($value),
            ]);
        }
        event(new DeleteListenerEvent(ListenerConst::SYS_CONFIG_UPDATE, ['key' => $key]));
    }
}
